<?php 

class ThumbHelper extends Helper
{

	function image($src, $width = null, $height = null, $transparent = "n")
	{		
		if($width==210&&$height==150){ //for testimonies
			$noImageFilename = IMAGES_URL."default_testimony.jpg";
		}
		else{
			$noImageFilename = IMAGES_URL."default.jpg";
		}
		
		if($src ==NULL || !is_file(IMAGES_URL . $src)) // check if src input is a file or folder
		{
			$srcImage = $noImageFilename;
			$sourceFilename = $noImageFilename;
		}
		else
		{
				$src = IMAGES_URL.$src;
				$srcImage = str_replace('//', '/', $src);
				$srcImage = str_replace('\\\\', '\\', $srcImage);
				$sourceFilename = str_replace('//', '/', WWW_ROOT.$src);
				$sourceFilename = str_replace('\\\\', '\\', $sourceFilename);
		
		}
		# if src file not found, and no-image.jpg is available
		if((!is_readable($sourceFilename) || !file_exists($sourceFilename)) && is_readable($noImageFilename))
		{
			# replace the file name and uri with no-image.jpg
			# process continue as normal
			# $uri = str_replace($srcImage, $noImageFilename, $uri);
			$sourceFilename = str_replace($srcImage, $noImageFilename, $sourceFilename);
		}
		if(is_readable($sourceFilename))
		{
			$src = $sourceFilename;
			$image_info = pathinfo($src);
			
			# get the width and height in either passed by argument or query string
			if ($width == NULL)
				$width 	= 0;
			
			if ($height == NULL)
				$height =  0;

			
			if($width==0 && $height == 0) $width = $height = 200;
			@$config_output_format = strtolower($image_info['extension']);
			$config_document_root = '';
			$config_temp_directory = APP . 'tmp';
			$config_cache_directory =WWW_ROOT.'img'.DS.'cache'.DS.'thumbs'.DS;
			$config_cache_disable_warning = true;
			if (!isset($this->passedArgs['t']))
				$transparent = (isset($_GET['t'])) ? $_GET['t'] : 'n';
			else
				$transparent = $this->passedArgs['t'];
			
			$cacheFilename = md5($src.'_w_x_h_'.$width.'_'.$height.'_'.$transparent);
			
			$cache_filename = $config_cache_directory.$cacheFilename.".".$config_output_format;

			$options = array('0' => array('w' => $width, 'h' => $height, 't' => $transparent));
			if(!is_file($cache_filename)){ // Check if image is already cached.
			
				if ($this->create_thumbnail($src, $cache_filename, $cacheFilename, $options)) {
				} else {
					die('Failed: Error 505');
				}

			}
			
			if(is_file($cache_filename)){ // If thumb was already generated we want to use cached version
				
				$cachedImage = getimagesize($cache_filename);
				return 'cache'.'/'.'thumbs'.'/'.$cacheFilename.'.'.$config_output_format;
								
								
			}
		}
		# if file is still not found, return nothing

	}
	
	
	# create thumbnail
	function create_thumbnail($pathToImages, $pathToThumbs, $fname, $options) {
		$image_info = pathinfo("{$pathToImages}");
		$image_type = strtolower($image_info['extension']);
		switch($image_type)
		{
			case "jpg":
			case "jpeg":
				$img = imagecreatefromjpeg("{$pathToImages}");
				break;
			case "png":
				$img = imagecreatefrompng("{$pathToImages}");
				break;
			case "gif":
				$img = imagecreatefromgif("{$pathToImages}");
				break;
			case "bmp":
				$img = $this->ImageCreateFromBMP("{$pathToImages}");
				break;
		}

		$width = imagesx( $img );
		$height = imagesy( $img );

		foreach($options as $type=>$options)
		{
			$new_width = $options['w'];
			$new_height = $options['h'];
			$ratio_orig = $width/$height;

			if(($height <= $new_height)&&($width<=$new_width) || ($height <= $new_height && $width == 0) || ($width <= $new_width && $height == 0)) {
				$new_width = $width;
				$new_height = $height;
			}
			else {
				if ($new_width == 0 || $new_height == 0) {
					if ($new_width == 0)
					{
						$new_width = $new_height*$ratio_orig;
					}
					else
					{
						$new_height = $new_width/$ratio_orig;
					}
				}
				elseif (($new_width/$new_height) > $ratio_orig) {
					$new_width = $new_height*$ratio_orig;
					// coz error occurred if width becomes lower than 1px
					if($new_width < 1)	$new_width = 1;
				}
				else {
					$new_height = $new_width/$ratio_orig;
					// coz error occurred if width becomes lower than 1px
					if($new_height < 1)	$new_height = 1;
				}
			}

			# force image return to be jpg
			$transparent = $options['t'];

			switch($image_type)
			{
				case "png":
					//header('Content-Type: '.$this->ImageTypeToMIMEtype('jpg'));
					$tmp_img = imagecreatetruecolor( $new_width, $new_height );
					imagesavealpha($tmp_img, true);
					if($transparent != 'y') {
						/* the last parameter alpha is a value between 0 and 127. 0 indicates completely opaque while 127 indicates completely transparent.  */
						$trans_colour = imagecolorallocatealpha($tmp_img, 255, 255, 255, 0);
					}
					else
						$trans_colour = imagecolorallocatealpha($tmp_img, 255, 255, 255, 127);
					imagefill($tmp_img, 0, 0, $trans_colour);
					$overlay = imagecreatefrompng("{$pathToImages}");
					$this->imageComposeAlpha('thumb', $tmp_img, $overlay, 0, 0, $new_width, $new_height);
					if($transparent != 'y') 
					{
						imagejpeg( $tmp_img, "{$pathToThumbs}", 100  );
					}
					else
						imagepng($tmp_img,"{$pathToThumbs}" );
					break;

				default:
					//header('Content-Type: '.$this->ImageTypeToMIMEtype('jpg'));
					$tmp_img = imagecreatetruecolor( $new_width, $new_height );
					imagecopyresampled( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
					imagejpeg( $tmp_img, "{$pathToThumbs}"  , 100);
					break;
			 }
		}
		return true;
	}

	function imageComposeAlpha($type, &$src, &$ovr, $ovr_x, $ovr_y, $ovr_w = false, $ovr_h = false, $angle = false)
	{
		if( $ovr_w && $ovr_h )
			$ovr = $this->imageResizeAlpha( $ovr, $ovr_w, $ovr_h);
		if(	$angle)
			$ovr = $this->imageRotateAlpha($ovr, $angle);
		if($type == "compose") {	
		/* Now compose the 2 images */
		imagecopy($src, $ovr, $ovr_x-imagesx($ovr)/2, $ovr_y - imagesy($ovr)/2, 0, 0, imagesx($ovr), imagesy($ovr) );
		}
		elseif ($type == "thumb") 
		{
		imagecopy($src, $ovr, $ovr_x, $ovr_y, 0, 0, imagesx($ovr), imagesy($ovr) );
		}
	}
	

	function imageRotateAlpha(&$src, $angle)
	{
		$temp = imagerotate($src, -$angle, -1);
		return $temp;
	}

	function imageResizeAlpha(&$src, $w, $h)
	{
		/* create a new image with the new width and height */
		$temp = imagecreatetruecolor($w, $h);
 
		/* making the new image transparent */
		$background = imagecolorallocate($temp, 0, 0, 0);
		imagecolortransparent($temp, $background); // make the new temp image all transparent
		imagealphablending($temp, false); // turn off the alpha blending to keep the alpha channel
 
		/* Resize the PNG file */
		/* use imagecopyresized to gain some performance but loose some quality */
		//imagecopyresized($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
		/* use imagecopyresampled if you concern more about the quality */
		imagecopyresampled($temp, $src, 0, 0, 0, 0, $w, $h, imagesx($src), imagesy($src));
		
		
		return $temp;
	}
}
?>